<?php


namespace api\project\controller;


use api\project\model\LoginModel;
use api\project\model\SmsCodeModel;
use api\project\validate\UserValidate;
use cmf\controller\RestBaseController;
use think\Request;

class UserController extends RestBaseController
{
        //注册api
        public function register(Request $request)
        {
            $data = $request->param();
            //验证器
            $validate = new UserValidate();
            $val = $validate->scene('register')->check($data);
            if(!$val)
            {
                $this->error($validate->getError());
            }

            //验证验证码
            CheckSmsCode($data['mobile'], $data['code']);
            //入库
            $res = LoginModel::create($data);
            if($res)
            {
               $this->success('注册成功');
            }else{
                $this->error('注册失败');
            }
        }
        //登录api
        public function login(Request $request)
        {
            $mobile = $request->param('mobile');
            $code = $request->param('code');

            if(empty($mobile))
            {
                $this->error('手机号码不能为空');
            }
            if(empty($code)){
                $this->error('验证码不能为空');
            }
            $res = LoginModel::where('mobile','=',$mobile)
                ->find();
            if(empty($res))
            {
                $this->error('手机号错误');
            }
            $sms = SmsCodeModel::where('mobile','=',$mobile)
                ->find();
            if(CheckSmsCode($mobile, $sms['code']))
            {
                $token = sendToken($res['id'],$mobile);
                $this->success(
                    '登录成功',
                    [
                        'data'=>$token
                    ]
                );
            }else{
                $this->error('登录失败');
            }
        }
        public function SentCode(Request $request)
        {
            $mobile = $request->param('mobile');
            //发送验证码
            sendAliSms($mobile);
        }
}